<?php

namespace apiend\modules\shop\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\shop\ShopGoods;

/**
 * CategoryProductSearch is the search model class for table "{{%dynamic}}".
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CategoryProductSearch extends \apiend\models\searchs\ProductSearch {

    /**
     * @var integer 主分类ID
     */
    public $pid;

    /**
     * @var integer 子分类ID
     */
    public $cid;

    /**
     * @var string 排序方式 sales、price、time
     */
    public $orderby = 'sales';

    /**
     * @var string 排序规则
     */
    public $sort = SORT_DESC;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['pid', 'cid', 'orderby', 'sort'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildQuery() {
        $query = static::find()->alias('t')->active(static::STATUS_ACTIVE);
        //栏目检索
        $query->innerJoinWith('categories cate', false);
        $query->andWhere(['cate.parent_id' => $this->pid]);
        $query->andFilterWhere(['cate.category_id' => $this->cid]);
        //检索排序
        $this->bindOrderBy($query);
        return $query;
    }

    /**
     * 绑定排序条件
     * @param \common\db\ActiveQuery $query 当前查询对象
     */
    public function bindOrderBy(&$query) {
        $query->innerJoinWith('stats s', true);
        $sort = strtoupper($this->sort) === 'DESC' ? SORT_DESC : SORT_ASC;
        $fields = [
            'sales' => 's.sales',
            'price' => 'price',
            'time' => 's.on_time',
        ];
        $column = ArrayHelper::getValue($fields, $this->orderby, 's.sales');
        if ($column === 'price') {
            $query->joinWith([
                'skus sku' => function ($query) use ($sort) {
                    $query->active(ShopGoods::STATUS_ACTIVE)->orderBy(['sku.price' => $sort]);
                }
            ]);
            $query->groupBy('t.id');
        } else {
            $query->orderBy([
                $column => $sort
            ]);
        }
    }

}
